/**
 * 将秒数格式化（x年x个月x天x小时x分x秒）
 * @param Int seconds 秒数
 * @return String format_time 格式化后的时间字符串
 */
function formatTimeSeconds(remain_seconds)
{
	// 计算年
	var format_year = remain_seconds / (86400 * 365);
	format_year = parseInt( format_year.toFixed(4) ) ;
	remain_seconds %= 86400 * 365;
	// 计算月
	var format_month = remain_seconds / (86400 * 30);
	format_month = parseInt( format_month.toFixed(4) );
	remain_seconds %= 86400 * 30;
	// 计算日
	var format_day = remain_seconds / 86400;
	format_day = parseInt( format_day.toFixed(4) );
	remain_seconds %= 86400;
	// 计算小时
	var format_hour = remain_seconds / 3600;
	format_hour = parseInt( format_hour.toFixed(4) );
	remain_seconds %= 3600;
	// 计算分钟
	var format_minute = remain_seconds / 60;
	format_minute = parseInt( format_minute.toFixed(4) );
	remain_seconds %= 60;
	// 拼装
	var format_time = format_year ? format_year + '年' : '';
	format_time = format_month ? format_month + '个月' : '';
	format_time += format_day ? format_day + '天' : '';
	format_time += format_hour ? format_hour + '小时' : '';
	format_time += format_minute ? format_minute + '分' : '';
	format_time += remain_seconds + '秒';

	return format_time;
}


/**
 * 加载进程池基本信息
 * @param Object/Array pool 进程池信息
 * @return Boolean
 */
function loadPoolBaseInfo(pool)
{
	// 处理进程池类型
	switch(pool['process manager'])
	{
		case 'static':
			pool['process manager'] = '静态（static）';
			break;
		case 'dynamic':
			pool['process manager'] = '动态（dynamic）';
			break;
		case 'ondemand':
			pool['process manager'] = '按需（ondemand）';
			break;
	}
	// 处理启动时间
	var local_date_options = {
		year: 'numeric',
		month: 'numeric',
		day: 'numeric',
		hour: 'numeric',
		minute: 'numeric',
		second: 'numeric'
	};
	var start_time = new Date(pool['start time'] * 1000);
	start_time = start_time.toLocaleDateString('zh-CN', local_date_options);
	// 处理运行时长
	var during_time = formatTimeSeconds(pool['start since']);
	// 处理进程池是否满载
	var pool_full = Boolean(pool['max children reached']) ? '是' : '否';
	// 加载基本信息
	$('#pool_name').text(pool['pool']);
	$('#pool_type').text(pool['process manager']);
	$('#start_time').text(start_time);
	$('#running_time').text(during_time);
	$('#finished_request').text(pool['accepted conn']);
	$('#penging_request').text(pool['listen queue']);
	$('#peak_penging_request').text(pool['max listen queue']);
	$('#waiting_queue_max_length').text(pool['listen queue len']);
	$('#idle_processes').text(pool['idle processes']);
	$('#active_processes').text(pool['active processes']);
	$('#total_processes').text(pool['total processes']);
	$('#peak_active_processes').text(pool['max active processes']);
	$('#pool_full').text(pool_full);
	$('#slow_requests').text(pool['slow requests']);

	return true;
}


/**
 * 加载进程列表
 * @param Object/Array process_list 进程列表
 * @return Boolean
 */
function loadProcessList(process_list)
{
	// 清理旧数据
	$('#pool_table table[name="process_list"]')
		.children('tbody')
		.children('tr:gt(1)')
		.remove();
	// 对列表按照pid进行升序排列
	process_list.sort(
		function(a, b)
		{
			return a['pid'] - b['pid'];
		}
	);
	// 循环处理数据
	var process_table_contents = '';
	for(i in process_list)
	{
		var process = process_list[i];
		// 处理状态
		switch(process['state'])
		{
			case 'Idle':
				process['state'] = '空闲';
				break;
			case 'Running':
				process['state'] = '活动';
				break;
		}
		// 处理启动时间
		var local_date_options = {
			year: 'numeric',
			month: 'numeric',
			day: 'numeric',
			hour: 'numeric',
			minute: 'numeric',
			second: 'numeric'
		};
		var start_time = new Date(process['start time'] * 1000);
		process['start time'] = start_time.toLocaleDateString('zh-CN', local_date_options);
		// 处理运行时长
		process['start since'] = formatTimeSeconds(process['start since']);
		// 生成表格类容
		process_table_contents += '<tr>';
		process_table_contents += '<td>' + process['pid'] + '</td>';
		process_table_contents += '<td>' + process['state'] + '</td>';
		process_table_contents += '<td>' + process['start time'] + '</td>';
		process_table_contents += '<td>' + process['start since'] + '</td>';
		process_table_contents += '<td>' + process['requests'] + '</td>';
		process_table_contents += '</tr>';
	}
	$('#pool_table table[name="process_list"]').append(process_table_contents);
}


/**
 * 加载图表
 */
function loadCharts()
{
	// 图表配置项
	var options = {
		legend: {
			orient: 'vertical',
			right: 10,
			top: 'center'
		},
		tooltip: {trigger: 'axis'},
		'dataset': {
			dimensions: [],
			'source': []
		},
		xAxis: {type: 'category'},
		yAxis: {type: 'value'},
		series: []
	};

	// 初始化图表
	var node_chart = $('#pool_chart')[0];
	var my_chart = echarts.init(node_chart, 'dark');
	// my_chart.setOption(options);
}


/**
 * 初始化进程池信息
 * 获取进程池完整信息，并渲染表格、图表
 */
function poolInfoInit()
{
	var pool_info = $.get(
		'../../fpm_status.php?fpm_ver=' + fpm_ver,
		function(res)
		{
			res = JSON.parse(res);
			if(res.status !== 1)
			{
				alert('获取进程池信息失败！');
				console.log(res['err_msg']);
			}
			res = res['data'];
			// 加载进程池基本信息
			loadPoolBaseInfo(res);
			// 加载进程列表
			loadProcessList(res['processes']);
			// 加载图表
			loadCharts();
		}
	);
}


$(document).ready(
	function()
	{
		// 引入公共头部，实现返回主页功能
		$('#toolbar').load('../../toolbar.html');

		// 页面载入时，初始化进程池信息，然后通过定时器周期性触发
		poolInfoInit();
		refresh_pool_info = setInterval('poolInfoInit()', refresh_speed);

		// 监听点击“实时刷新”开关
		$(document).on(
			'click',
			'#update_realtime',
			function()
			{
				// 获取当前开关状态
				var current_switch = $(this).attr('data-status');
				// 计算新的开关状态、开关图片，切换并执行对应操作
				switch(current_switch)
				{
					case 'on':
						var new_status = 'off';
						var new_img = '../../src/switch-off.svg';
						// 停止实时更新
						clearInterval(refresh_pool_info);
						break;
					case 'off':
						var new_status = 'on';
						var new_img = '../../src/switch-on.svg';
						// 恢复实时更新，并立即执行
						refresh_pool_info = setInterval('poolInfoInit()', refresh_speed);
						poolInfoInit();
						break;
				}
				$(this).attr('data-status', new_status);
				$(this).find('img').attr('src', new_img);
			}
		);

		// 监听滚动条位置，当超过窗口可用高度时，显示“返回顶部”按钮
		$(window).scroll(
			function()
			{
				if( $(window).scrollTop() > 1 )
				{
					$('#goto_top').show();
				}
				else
				{
					$('#goto_top').hide();
				}
			}
		);

		// 监听点击“返回顶部”
		$('#goto_top').click(
			function()
			{
				// 平滑回滚
				$('html, body').animate(
					{scrollTop: 0},
					350
				);
			}
		);

		// 页面大小发生变化时，自动调整图表尺寸
		$(window).resize(
			function()
			{
				my_chart.resize();
			}
		);

	}
);
